package BTconn;

import java.io.IOException;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;



/**
 * Controller class that handles all events that are occuring in application
 * @author m4rt1n
 */
public class Controler extends MIDlet implements CommandListener, DiscoveryListener {


    private static Controler instance;
    private static Form f;
    private int id = 0;

    public static Controler getInstance()
    {
        return instance;
    }

    public static void showAlert(String title, String msg)
    {
        f = new Form(title);
        f.append(msg);
        try {
            Displayable old = Display.getDisplay(Controler.getInstance()).getCurrent();
            Display.getDisplay(Controler.getInstance()).setCurrent(f);
            Thread.sleep(3000);
            Display.getDisplay(Controler.getInstance()).setCurrent(old);
        }catch(IllegalArgumentException e){
    //            e.
        }catch(InterruptedException e){
    //            e.
        }
    }

    /**
     * An instance of a GpsBtController class
     */
    private GpsBtController gbc = null;

    /**
     * An instance of a MIDmenu class
     */
    private MIDmenu gui;


    /**
     * Constructor
     */
    public Controler()
    {
        instance = this;
        gui = new MIDmenu(this);
    }

    /**
     * Method triggered by the Discovery Listener
     * when the device is found in range
     */
    public void addDeviceNameToList()
    {
        String label = gbc.getDiscoveredDevName();
        gui.addLabelOnMenuPosition(label, MIDmenu.DEV_MENU);
    }


    /**
     * Method called after MIDlet is turned off
     */
    protected void destroyApp(boolean unconditional)
    {
        if(gbc!=null)
        {
            try
            {
                gbc.ld.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
            } catch (BluetoothStateException ex) {
                ex.printStackTrace();
                System.err.println("Failed to set device to NOT_DISCOVERABLE while destroying app");
            }

            gbc = null;
        }
        notifyDestroyed();
    }

    /**
     * Method called after MIDlet is paused
     */
    protected void pauseApp()
    {
    }

    /**
     * Method called after MIDlet is turned on
     */
    protected void startApp()
    {
        gui.setActiveMenu(MIDmenu.MAIN_MENU);
    }

    /**
     * Commands listener
     */
    public void commandAction (Command c, Displayable d)
    {
        if (c == gui.EXIT_CMD)
        {
            destroyApp(true);

            return;
        }


        if (gui.isMenuOpened)
        {
            switch (gui.getSelectedListIndex(gui.menu))
            {
                case 0:
                    String[] devicesNames = null;

                    if (gbc==null)
                        gbc = new GpsBtController(this);

                    gbc.search4Devices();

                    if (gbc.isDevDiscovered())
                    {
                        devicesNames = gbc.getDeviceNames();
                    }
                    else
                    {
                        if(!gbc.isInquiryCompleted())
                        {
                            devicesNames = new String[1];
                            devicesNames[0] = MIDmenu.WAIT_DEV_TITLE;
                        }
                        else
                        {
                            gbc.search4Devices();
                            devicesNames = new String[1];
                            devicesNames[0] = MIDmenu.WAIT_DEV_TITLE;
                        }
                    }
                    gui.setDevElements(devicesNames);
                    gui.setActiveMenu(MIDmenu.DEV_MENU);


                    break;

                case 1:
                    destroyApp(true);
                    notifyDestroyed();

                    break;

                default:
                    System.err.println ("Unexpected choice...");

                    break;
            }

        }
        else if(gui.isDevMenuOpened)
        {
//              switch (gui.getSelectedListIndex(gui.devicesList))
//              {
//                  case 0:
            if (c.getCommandType() == Command.SCREEN)
            {
                String[] servicesNames = null;
            System.out.println("KLIKŁEŚ OKEJ");
                id = gui.getSelectedListIndex(gui.devicesList);

            System.out.println("Dajesz ID takie"+id);
                gbc.search4Services(id);

                if(gbc.isServiceDiscovered())
                {
                    servicesNames = gbc.getServiceNames();
                }
                else
                {
                    if(!gbc.isServiceSearchCompleted())
                    {
                        servicesNames = new String[1];
                        servicesNames[0] = MIDmenu.WAIT_SER_TITLE;
                    }
                    else
                    {
                        gbc.search4Services(id);
                        servicesNames = new String[1];
                        servicesNames[0] = MIDmenu.WAIT_SER_TITLE;
                    }
                }

               // gui.clearMenu(MIDmenu.DEV_MENU);
                gui.setServicesElements(servicesNames);
                gui.setActiveMenu(MIDmenu.SERVICES_MENU);
            }

            if (c == gui.REFRESH_CMD)
            {
            System.out.println("KLIKŁEŚ rifresz");
                //String[] deviceName;
                if (gbc.isInquiryCompleted())
                {
                    gui.clearMenu(MIDmenu.DEV_MENU);
                    gui.addLabelOnMenuPosition(MIDmenu.WAIT_DEV_TITLE, MIDmenu.DEV_MENU);
                    gbc.resetRemoteDevices();
                    gbc.resetNumberOfDevices();
                    gbc.search4Devices();
                }
    //                        else
    //                        {
    //                            gui.clearMenu(MIDmenu.DEV_MENU);
    //                            deviceName = new String[1];
    //                            deviceName[0] = MIDmenu.WAIT_TITLE;
    //                            gbc.searchDevices();
    //                        }
            }

            if (c == gui.BACK_CMD)
            {
                if (!gbc.isInquiryCompleted())
                {
                    gbc.dA.cancelInquiry(gbc);
                    System.out.println("inquiry canceled!");
                }
                gbc.resetNumberOfDevices();
                gbc.resetRemoteDevices();
                gui.setActiveMenu(MIDmenu.MAIN_MENU);
                return;
            }
        }
        else if(gui.isServMenuOpened)
        {
            if (c == gui.REFRESH_CMD)
            {
                if (gbc.isServiceSearchCompleted())
                {
                    gui.clearMenu(MIDmenu.SERVICES_MENU);
                    gui.addLabelOnMenuPosition(MIDmenu.WAIT_SER_TITLE, MIDmenu.SERVICES_MENU);
                    gbc.search4Services(id);
                }
            }
            if (c == gui.BACK_CMD)
            {
                if (!gbc.isServiceSearchCompleted())
                {
                    gbc.dA.cancelServiceSearch(id);
                    System.out.println("service search canceled!");
                }
                gui.setActiveMenu(MIDmenu.DEV_MENU);
                return;
            }
        }
        
    }
    
    public void deviceDiscovered(RemoteDevice rd, DeviceClass dc)
    {
//        Display d = Display.getDisplay(this);
//        try
//        {
//            d.setCurrent(new Alert("Znalazlem!", "Znaleziono " + rd.getFriendlyName(true), null, AlertType.INFO));
//        }
//        catch (IOException ex)
//        {
//            ex.printStackTrace();
//        }
        String[] deviceName = gbc.getDeviceNames();

        gui.setDevElements(deviceName);
        gui.refreshList(gui.devicesList);

        
    }

    public void inquiryCompleted(int dType)
    {
        //Display d = Display.getDisplay(this);
        //d.setCurrent(new Alert("Inquiry Completed!", "Found " + gbc.getNumberOfDevices() + " devices.\n" , null, AlertType.INFO));

        String[] deviceName = gbc.getDeviceNames();

        if(deviceName.length==0)
        {
            deviceName = new String[1];
            deviceName[0] = MIDmenu.NO_DEVICES;
            gui.setDevElements(deviceName);
            gui.refreshList(gui.devicesList);
        }

       // gbc.resetNumberOfDevices();
        //gbc.resetRemoteDevices();
    }

    public void serviceSearchCompleted(int transID, int respCode)
    {
        System.out.println("SUPER KONIEC SZUKANIA KURWO");
        String[] servicesNames = null;
        servicesNames = gbc.getServiceNames();
        
        if(servicesNames==null)
        {
            servicesNames = new String[1];
            servicesNames[0] = MIDmenu.NO_SERVICES;
            gui.setServicesElements(servicesNames);
            gui.refreshList(gui.servicesList);
        }
        else
        {
            gui.setServicesElements(servicesNames);
            gui.refreshList(gui.servicesList);
        }
//        Display d = Display.getDisplay(this);
//        d.setCurrent(new Alert("Service Search Completed!", "Found xxxx services. "+respCode, null, AlertType.INFO));
//        try {
//            Thread.sleep(2000);
//        } catch (InterruptedException ex) {
//            ex.printStackTrace();
//        }
                            gui.clearMenu(MIDmenu.SERVICES_MENU);
                    gui.addLabelOnMenuPosition(MIDmenu.WAIT_SER_TITLE, MIDmenu.SERVICES_MENU);
        gbc.search4Services(id);
    }

    public void servicesDiscovered(int transID, ServiceRecord[] sR)
    {
        Display d = Display.getDisplay(this);
        d.setCurrent(new Alert("Service discovered!", "Found service." + sR.toString() , null, AlertType.INFO));
    }


}
